package com.baijiayun.live.ui.interactivepanel

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.base.BasePadFragment
import com.baijiayun.live.ui.base.getViewModel
import com.baijiayun.live.ui.chat.ChatPadFragment
import com.baijiayun.live.ui.chat.ChatViewModel
import com.baijiayun.live.ui.onlineuser.OnlineUserFragment
import com.baijiayun.live.ui.onlineuser.OnlineUserViewModel
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.fragment_pad_interactive.*

/**
 * Created by Shubo on 2019-10-10.
 */
class InteractiveFragment : BasePadFragment() {

    private lateinit var interactiveContainer: ViewGroup
    private lateinit var tabLayout: TabLayout
    private lateinit var viewPager: ViewPager

    private var chatRedTipTv: TextView? = null
    private lateinit var userTabItemTv: TextView

    private val userViewModel by lazy {
        activity?.run {
            getViewModel { OnlineUserViewModel(routerViewModel.liveRoom) }
        }
    }

    private val chatViewModel by lazy {
        activity?.run {
            getViewModel { ChatViewModel(routerViewModel) }
        }
    }

    private var shouldShowMessageRedPoint = true
    private var shouldShowQARedPoint = true

    /**
     * 学生和老师的tabs分别读取配置项
     * 问答和用户列表tabs和各自的配置项都满足才显示
     */
    private val liveFeatureTabs by lazy {
        if ((routerViewModel.liveRoom.partnerConfig.liveFeatureTabs.isNullOrEmpty() && isTeacherOrAssistant())
            || (routerViewModel.liveRoom.partnerConfig.liveStudentFeatureTabs.isNullOrEmpty() && !isTeacherOrAssistant())
        ) {
            ArrayList()
        } else {
            val list =
                if (isTeacherOrAssistant()) routerViewModel.liveRoom.partnerConfig.liveFeatureTabs.split(",")
                else routerViewModel.liveRoom.partnerConfig.liveStudentFeatureTabs.split(",")
            val tabList = ArrayList(list)
            tabList.remove(LABEL_SPEAKER)
            tabList.remove(LABEL_ANSWER)
            //问答调整至ppt页面，tab只有user和chat
            if (tabList.size >= 3) {
                val iterator = tabList.iterator()
                while (iterator.hasNext()) {
                    val next = iterator.next()
                    if (next != LABEL_CHAT && next != LABEL_USER) {
                        iterator.remove()
                    }
                }
            }
            if (routerViewModel.liveRoom.partnerConfig.liveHideUserList == 1) {
                tabList.remove(LABEL_USER)
            }
            tabList
        }
    }

    private val navigateToMainObserver by lazy {
        Observer<Boolean> {
            if (it == true) {
                initSuccess()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun observeActions() {
        routerViewModel.actionNavigateToMain.observeForever(navigateToMainObserver)
    }

    @SuppressLint("SetTextI18n")
    private fun initSuccess() {
        initView()
        shouldShowQARedPoint = liveFeatureTabs.size > 1 && liveFeatureTabs[0] != LABEL_ANSWER
        shouldShowMessageRedPoint = liveFeatureTabs.size > 1 && liveFeatureTabs[0] != LABEL_CHAT
        routerViewModel.action2ChatBottom.value = liveFeatureTabs.size > 1 && liveFeatureTabs[0] == LABEL_CHAT
        if (liveFeatureTabs.contains(LABEL_USER)) {
            userViewModel?.onlineUserCount?.observe(this, Observer {
                userTabItemTv.text = "${getString(R.string.user)}($it)"
            })
        }

        if (liveFeatureTabs.size > 1 && liveFeatureTabs.contains(LABEL_CHAT)) {
            chatViewModel?.redPointNumber?.observe(this, Observer {
                it?.let {
                    showChatRedPoint(it)
                }
            })
        }
    }

    private fun showChatRedPoint(redPointNumber: Int) {
        if (shouldShowMessageRedPoint && redPointNumber > 0) {
            chatRedTipTv?.visibility = View.VISIBLE
            chatRedTipTv?.text = if (redPointNumber > 99) ".." else redPointNumber.toString()
        } else {
            chatRedTipTv?.visibility = View.GONE
        }
    }


    override fun init(view: View) {
        interactiveContainer = view.findViewById(R.id.interactive_container)
        tabLayout = view.findViewById(R.id.user_chat_tablayout)
        tabLayout.setTabTextColors(
            ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color),
            ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color)
        )
        tabLayout.setSelectedTabIndicatorColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
        viewPager = view.findViewById(R.id.user_chat_viewpager)
    }

    private fun initView() {
        routerViewModel.chatLabelVisiable = liveFeatureTabs.contains(LABEL_CHAT)
        if (liveFeatureTabs.size == 1) {
            tabLayout.setSelectedTabIndicatorColor(Color.TRANSPARENT)
        }
        initViewpager()
        initTabLayout()
    }

    private fun initTabLayout() {
        routerViewModel.action2Chat.value = !liveFeatureTabs.isNullOrEmpty() && liveFeatureTabs[0] == LABEL_CHAT
        tabLayout.setupWithViewPager(viewPager)
        for (i in liveFeatureTabs.indices) {
            val tabView = getTabView()
            tabLayout.getTabAt(i)?.customView = tabView
            val tabItemTv = tabView.findViewById<TextView>(R.id.item_chat_tv)
            when (liveFeatureTabs[i]) {
                LABEL_CHAT -> chatRedTipTv = tabView.findViewById(R.id.item_red_tip_tv)
                LABEL_USER -> {
                    userTabItemTv = tabItemTv
                }
            }
            if (i == 0) {
                context?.run { ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color) }?.let {
                    tabItemTv.setTextColor(it)
                }
            }
            tabItemTv.text = getStringByTag(liveFeatureTabs[i])
        }
        tabLayout.addOnTabSelectedListener(object : TabLayout.BaseOnTabSelectedListener<TabLayout.Tab> {
            override fun onTabUnselected(tab: TabLayout.Tab?) {
                context?.run { ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color) }?.let {
                    tab?.customView?.findViewById<TextView>(R.id.item_chat_tv)?.setTextColor(it)
                }
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                context?.run { ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color) }?.let {
                    tab?.customView?.findViewById<TextView>(R.id.item_chat_tv)?.setTextColor(it)
                }
            }

            override fun onTabReselected(p0: TabLayout.Tab?) {
                // do nothing
            }
        })
    }

    private fun getTabView(): View {
        return LayoutInflater.from(context).inflate(R.layout.chat_custom_tab_item, user_chat_tablayout, false)
    }

    private fun initViewpager() {
        viewPager.adapter = object : androidx.fragment.app.FragmentStatePagerAdapter(childFragmentManager) {
            override fun getItem(position: Int): androidx.fragment.app.Fragment {
                return getFragmentByTag(liveFeatureTabs[position])
            }

            override fun getCount(): Int {
                return if (liveFeatureTabs.size == 3) liveFeatureTabs.size - 1 else liveFeatureTabs.size
            }
        }

        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(p0: Int) {
                // do nothing
            }

            override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
                // do nothing
            }

            override fun onPageSelected(p0: Int) {
                routerViewModel.action2ChatBottom.value = liveFeatureTabs[p0] == LABEL_CHAT
                shouldShowMessageRedPoint = liveFeatureTabs[p0] != LABEL_CHAT
                if (!shouldShowMessageRedPoint) {
                    chatViewModel?.redPointNumber?.value = 0
                    routerViewModel.action2Chat.value = true
                } else {
                    routerViewModel.action2Chat.value = false
                }
            }
        })
    }

    override fun getLayoutId(): Int = R.layout.fragment_pad_interactive

    override fun onDestroyView() {
        super.onDestroyView()
        routerViewModel.actionNavigateToMain.removeObserver(navigateToMainObserver)
    }

    companion object {
        const val LABEL_CHAT = "chat"
        const val LABEL_ANSWER = "answer"
        const val LABEL_USER = "user"
        const val LABEL_SPEAKER = "speaker"
        fun newInstance() = InteractiveFragment()
    }

    private fun getFragmentByTag(tag: String): androidx.fragment.app.Fragment {
        return when (tag) {
            LABEL_CHAT -> ChatPadFragment()
            else -> OnlineUserFragment()
        }
    }

    private fun getStringByTag(tag: String): String? {
        return when (tag) {
            LABEL_CHAT -> context?.getString(R.string.chat)
            LABEL_USER -> context?.getString(R.string.user)
            else -> ""
        }
    }
}